<template>
	<view class="box">
		<!-- 选择会员 -->
		<view class="selectMember">
			<view class="member">
				<text style="position: relative;">{{start_date || '日期：'}}
					<picker mode="date" :start="start" :end="end"  @change="bindDateChange" v-if="!selected" style="position: absolute;left:0;top: 0;width: 100%;height: 100%;">
					</picker> 
				</text>
			</view>
			<view :class="number == 1 && !id ? 'disabled' : 'save'" @click="showModalbtn(4)" v-if="!selected">保存</view>
			<view :class="number == 1 && !id ? 'disabled' : 'toSend'" @click="selected != 1 ? showModalbtn(2) : ''" >申请评估</view>
		</view>
		
		<view class="screenModular">
			<view class="pageOne" v-if="number == 1">
				<view class="constitutionModular" v-for="(item,index) in questionnaire" :key="index">
					<image src="@/static/img/healthStatus/constitutionPin.png" class="constitutionImg" v-if="index == 0"></image>
					<image src="@/static/img/healthStatus/constitutionQiXu.png" class="constitutionImg" v-else-if="index == 1"></image>
					<image src="@/static/img/healthStatus/constitutionYang.png" class="constitutionImg" v-else-if="index == 2"></image>
					<image src="@/static/img/healthStatus/constitutionYin.png" class="constitutionImg" v-else-if="index == 3"></image>
					<image src="@/static/img/healthStatus/constitutionTan.png" class="constitutionImg" v-else-if="index == 4"></image>
					<image src="@/static/img/healthStatus/constitutionShi.png" class="constitutionImg" v-else-if="index == 5"></image>
					<image src="@/static/img/healthStatus/constitutionXue.png" class="constitutionImg" v-else-if="index == 6"></image>
					<image src="@/static/img/healthStatus/constitutionYu.png" class="constitutionImg" v-else-if="index == 7"></image>
					<image src="@/static/img/healthStatus/constitutionBing.png" class="constitutionImg" v-else-if="index == 8"></image>
					
					<view class="questionModular">
						<view class="single" v-for="(aitem,aindex) in item.adTopicsRepliesEntityList" :key="aindex">
							<view class="title">
								<text>{{aindex <= 8 ? '0'+(aindex+1) : aindex+1}}</text>
								<view>{{aitem.name}}</view>
							</view>
							<view class="answer">
								<text  v-for="(bitem,bindex) in aitem.adTopicsRepliesEntityList" :key="bindex" @click="answer(aitem,bitem)" :class="bitem.checked == true ? 'checked' : ''">{{bitem.value && bitem.value.substr(0,2)}}</text>
							</view>
						</view>
					</view>		
				</view>
				<view class="nextPage" @click="nextPage">下一页</view>
			</view>
			<view class="pageTwo" v-if="number == 2">
				<view class="constitutionModular">
					<view class="lookingFor">
						<image src="@/static/img/healthStatus/lookingFor@2x.png" class="constitutionImg"></image>
						<text @click="see">判断标准</text>
					</view>
					<view class="questionModular">
						<view class="question" v-for="(sitem,sindex) in lookAndSmellDetails" :key="sindex">
							<view class="title">
								<text>{{sindex <= 8 ? '0'+(sindex+1) : sindex+1}}</text>
								<view>{{sitem.name}}</view>
							</view>
							<view class="option">
								<view v-for="(ditem,dindex) in sitem.adTopicsRepliesEntityList" :key="dindex" @click="change(sitem,ditem)">
									<image src="@/static/img/select@2x.png" v-if="ditem.checked == false"></image>
									<image src="@/static/img/selected@2x.png" v-else></image>
									<text>{{ditem.value}}</text>
								</view>
							</view>
						</view>
					</view>					
				</view>
				
				<view class="constitutionModular">
					<image src="@/static/img/healthStatus/conversionScore@2x.png" class="conversionScore"></image>
					<view class="chart">
						<tr>
							<th>体质类型</th>
							<th>转化分数</th>
							<th>分数对应</th>
						</tr>
						<tr v-for="(item,index) in conversionScore" :key="index">
							<td>{{item.typeName}}</td>
							<td>{{item.score}}</td>
							<td>{{item.result}}</td>
						</tr>
					</view>
				</view>	
				<view class="nextPage" @click="number = number - 1">上一页</view>
			</view>
		</view>
		<u-modal v-model="showPopup" :show-cancel-button="true" @confirm="showPopup = false" :content="showContent"></u-modal>
	</view>
</template>

<script>
	import {getUrlParam} from '@/static/js/filter.js'
	export default{
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				start:'',
				end:currentDate,
				start_date:'',
				userName:'',
				// constitutionArray:['平和质 ','痰湿质','气虚质','阳虚质 ','阴虚质','湿热质','血瘀质','气郁质','特禀质 '],
				number:1,
				questionnaire:{}, //问
				sex:'',
				lookAndSmellDetails:{}, //望闻切
				showPopup: false,
				showContent: '',
				conversionScore:{}, //转化分
				appUserTopicsEntities1:[], //望闻切选项
				id: '', //编辑id
				data1:[], //接口返回的选项
				selected:'', //申请之后再进来查看的状态
				
			}
		},
		created() {
			this.conversionScore = localStorage.getItem('conversionScore') ? localStorage.getItem('conversionScore') && JSON.parse(localStorage.getItem('conversionScore')) : this.conversionScore;
			this.sex = localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).sex;
			this.selected = getUrlParam('selected');
			this.questionArr().then((reponse) => {
				this.lookAndSmellQuestion()
				if(reponse) {
					if(!localStorage.getItem('rapidScreen') && getUrlParam('id') || getUrlParam('id')) {
						this.interface()	
					}else if(localStorage.getItem('rapidScreen')) {
						this.cache();
					}		
				}
			});
			
			
		},

		methods:{
			//接口返回的数据
			interface() {
				if(getUrlParam('id')) {
					const _this = this;
					_this.id = getUrlParam('id');
					_this.$api.psychologyQuestionInfo(_this.id).then((res) => {
						if(res.data.returnCode == 200) {
							const data1 = res.data.result && res.data.result.newUserTopicsEntities;
							const data2 = res.data.result && res.data.result.newAppMentalHealthAssessmentEntity;
							_this.userId = data2.userId;
							_this.healthId = data2.healthId;
							_this.start_date = data2.fillFormDate;
							_this.editTid = data2.tid;
							_this.conversionScore = data2.appPhysiqueScoreVos
							_this.questionnaire && _this.questionnaire.map((a) => { //问
								a && a.adTopicsRepliesEntityList.map((b) => {
									data1.map((c) => {											
										if(b.id == c.titleId) {
											b.adTopicsRepliesEntityList.map((d) => {
												d.nid = c.id;
												if(d.elections == c.userOption) {
													d.checked = true;
												}
											})
										}
									})
								})
							})
							_this.lookAndSmellDetails && _this.lookAndSmellDetails.map((a) => {
								a.adTopicsRepliesEntityList.map((b) => {
									data1.map((c) => {
										if(a.id == c.titleId) {
											b.nid = c.id;
											if (c.userOption && c.userOption.split(',').length > 1) {
												//多选
												c.userOption && c.userOption.split(',').map((e) => {
													if (e == b.elections) {
														b.checked = true
													}
												})
											} else {
												//单选
												if (b.elections == c.userOption) {
													b.checked = true;
												}
											}
										}
									})
								})
							})
						}
					})
				}
			},
			//望闻切（缓存）
			// lookSmell() {
			// 	this.lookAndSmellDetails = localStorage.getItem('smellDetails')&& JSON.parse(localStorage.getItem('smellDetails')).map((a) => {
			// 		a.adTopicsRepliesEntityList.filter((b) => {
			// 			return b.checked
			// 		})
			// 		return a
			// 	})
			// },
			//点击上一页  假如缓存中有选中的数据  问
			cache() {
				this.questionnaire = localStorage.getItem('rapidScreen')&& JSON.parse(localStorage.getItem('rapidScreen')).map((a) => {
					a.adTopicsRepliesEntityList.map((b) => {
						b.adTopicsRepliesEntityList.filter((c) => {
							return c.checked
						})
						return b
					})
					return a
				})
			},

			//选答案
			answer(aitem,bitem) {
				if(this.selected == 1) {
					return
				}
				const answerArr = aitem.adTopicsRepliesEntityList.map((a) => {
					a.checked = false;
					return a
				})
				bitem.checked = true;
				localStorage.setItem('rapidScreen',JSON.stringify(this.questionnaire)) //问 存选项
			},
			//望闻切选择答案
			change(sitem,ditem) {
				if(this.selected == 1) {
					return
				}
				ditem.checked = !ditem.checked;
				localStorage.setItem('smellDetails',JSON.stringify(this.lookAndSmellDetails)) //望闻切 存选项
			},
			//下一页
			nextPage() {
				//判断是否有未选择答案的问题
				const aresult = this.questionnaire && this.questionnaire.map((a) => {
					const bresult = a.adTopicsRepliesEntityList.map((b) => {
						const cresult = b.adTopicsRepliesEntityList.filter((c) => {
							return c.checked
						})	
						return b.bresult = cresult
					})			
					return a
					
				})
				var noSelected = []
				const dArr = aresult.map((d)=>{
					var fArr = d.adTopicsRepliesEntityList.filter((f) => {
						if(f.bresult.length <= 0) {
							f.headline = d.adTopicsEntity.name;
							noSelected.push(f)
						}
						return f
					})
					
					return d
				})
				
				if(noSelected.length > 0) {
					this.showPopup = true,
					this.showContent = '请选择'+noSelected[0].headline +'下的'+noSelected[0].name
					return 
				}
				//用户选择的值
				this.appUserTopicsEntities1 = []
				this.questionnaire.map((a) => {
					a.adTopicsRepliesEntityList.map((b) => {
						let bresult = b.adTopicsRepliesEntityList.filter((c) => {
							return c.checked
						});
						this.appUserTopicsEntities1.push({
							titleId: b.id,
							id: bresult.length > 0 && bresult[0].nid || b.adTopicsRepliesEntityList[0].nid,
							userOption: bresult.length > 0 ? bresult[0].elections : '',
							type:b.type,
							userNumber:bresult.length > 0 ? bresult[0].numbers : '',
							userValue: bresult.length > 0 ? bresult[0].value : ''
						})
					})
				})
				
				const record = {
					appUserTopicsEntities: this.appUserTopicsEntities1,
					healthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
					appUserTopicsTitleEntity: {
						healthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
						userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					},
					source:1,
					// status:2,
					tid:[30,31,32,33,34,35,36,37,38],
					upload:7,
					userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					
				}
				if(this.selected == 1 || this.id && !localStorage.getItem('rapidScreen')) {
					this.number = this.number + 1;
				}else {
					this.$api.AppMentalHealthAssessmentRefresh(record).then((res) => {
						if(res.data.returnCode == 200) {
							this.number = this.number + 1;
							this.conversionScore = res.data.result;
							localStorage.removeItem('rapidScreen');
							localStorage.setItem('conversionScore',JSON.stringify(this.conversionScore)); //存分数
							localStorage.setItem('appUserTopicsEntities1',JSON.stringify(this.appUserTopicsEntities1)); //存过滤好的后续保存一起的66道题 选项
						}
					})
				}
				
				
			},
			//申请评估
			showModalbtn(e) {
				if(!this.start_date) {
					uni.showToast({
						title: '请选择日期',
						icon: 'none'
					})
					return
				}
				let appUserTopicsEntities = [];  //当第一次计算完之后  数组里面有数据  在计算的话先清空掉
				this.lookAndSmellDetails.map((a) => {
					const lookBresult = a.adTopicsRepliesEntityList.filter((b) => {
						return b.checked
					})
					let elections = '';
					let userValue = '';
					lookBresult.map((a) => {
						elections += a.elections + ',';
						userValue += a.value + ','
					})
					elections = elections.substring(0, elections.lastIndexOf(","));
					userValue = userValue.substring(0, userValue.lastIndexOf(","));

					appUserTopicsEntities.push({
						titleId: a.id,
						id: lookBresult.length > 0 && lookBresult[0].nid || a.adTopicsRepliesEntityList[0].nid,
						type: a.type,
						userOption: lookBresult.length > 0 ? elections : '',
						userValue: lookBresult.length > 0 ? userValue : '',
					})
				})
				appUserTopicsEntities = appUserTopicsEntities.concat(this.appUserTopicsEntities1.length > 0 ? this.appUserTopicsEntities1 : JSON.parse(localStorage.getItem('appUserTopicsEntities1')));
				const record = {
					appUserTopicsEntities: appUserTopicsEntities,
					healthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
					appUserTopicsTitleEntity: {
						healthId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).healthId ||'',
						userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					},
					fillFormDate: this.start_date,
					source:1,
					status:e,
					tid:[39,30,31,32,33,34,35,36,37,38],
					upload:7,
					userId: localStorage.getItem('userInfo') && JSON.parse(localStorage.getItem('userInfo')).userId || '',
					
				}
				localStorage.removeItem('conversionScore');
				localStorage.removeItem('smellDetails');
				localStorage.removeItem('appUserTopicsEntities1');
				if(this.id) {
					record.id = Number(this.id);
					record.appUserTopicsTitleEntity.id = this.editTid
					this.$api.psychologyQuestionUpdate(record).then((res) => {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateTo({
								url:'/pages/healthStatus/navigation?current=6'
							})
						},2000)
					})
				}else {
					this.$api.psychologyQuestionAdd(record).then((res) => {
						if(res.data.returnCode == 200) {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
							setTimeout(() => {
								uni.navigateTo({
									url:'/pages/healthStatus/navigation?current=6'
								})
							},2000)
						}
					})
				}
				
			},
			// 获取题目
			questionArr(){
				return new Promise((success,error)=>{
					this.$api.psychologyQuestion('ids=30&ids=31&ids=32&ids=33&ids=34&ids=35&ids=36&ids=37&ids=38').then((res)=>{
						if(res){
							const data =  Object.keys(res.data.result).map((a)=>{
								const aData =  res.data.result[a].adTopicsRepliesEntityList.map((b)=>{
									b.adTopicsRepliesEntityList.map((c)=>{c.checked = false;return b})
									return b
								})
								return res.data.result[a]
							})
							this.sex == 2 ? data[5].adTopicsRepliesEntityList.splice(6,1): data[5].adTopicsRepliesEntityList.splice(5,1);
							this.questionnaire = data;
							success(res.data.result)
						}else{
							error('')
						}
					})
				})
			},
			// 望闻切题目
			lookAndSmellQuestion() {
				return new Promise((success,error) => {
					this.$api.psychologyQuestion('ids=39').then((res) => {
						if(res) {
							this.lookAndSmellDetails = res.data.result[39] && res.data.result[39].adTopicsRepliesEntityList.map((a) => {
								a.adTopicsRepliesEntityList.map((b) => {
									return b.checked = false
								})
								return a
							});
							success(res.data.result[39])
						}else {
							error('')
						}
					})
				})
			},
			see() {
				uni.navigateTo({
					url:'/pages/healthStatus/chineseMedicine/criteria'
				})
			},
			// 日期
			bindDateChange(e) { 
				this.start_date = e.target.value;
			},
			// 获取当前时间
			getDate(type) {
			   const date = new Date();
			   let year = date.getFullYear();
			   let month = date.getMonth() + 1;
			   let day = date.getDate();
			  
			   if (type === 'start') {
				year = year - 60;
			   } else if (type === 'end') {
				year = year + 2;
			   }
			   month = month > 9 ? month : '0' + month;;
			   day = day > 9 ? day : '0' + day;
			   return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/css/monitor/accomplishment/index.scss';
	.disabled {
		background-color: #cccccc !important;
		width: 69px;
		height: 31px;
		line-height: 31px;
		text-align: center;
		border-radius: 4px;
		color: #FFFFFF;
		margin-right: 18upx;
	}
	.disabled:last-child {
		margin-right: 0;
	}
	.constitutionModular {
		margin-top: 28upx;
		.lookingFor {
			position: relative;
			text {
				position: absolute;
				right: 0;
				top: 50%;
				transform: translateY(-50%);
				color: #05C6AD;
				font-size: 28upx;
			}
		}
		.constitutionImg,.conversionScore {
			width: 336upx;
			height: 48upx;
			display: table;
			margin: auto;
		}
		.conversionScore {
			width: 264upx;
			height: 38upx;
			margin: 35upx auto;
		}
		.questionModular {
			width: 702upx;
			background: #FFFFFF;
			border-radius: 14upx;
			margin-top: 25upx;
			padding: 27upx 20upx 0;
			box-sizing: border-box;
			.single,.question {
				margin-top: 34upx;
				padding: 0 0 40upx;
				border-bottom: 1upx solid #DADADA;
				.title {
					display: flex;
					color: #333333;
					font-size: 30upx;
					text {
						width: 40upx;
						height: 26upx;
						line-height: 26upx;
						background: #05C6AD;
						border-radius: 14upx;
						color: #FFFFFF;
						font-size: 26upx;
						display: inline-block;
						text-align: center;
						margin-right: 18upx;
						margin-top: 6upx;
					}
					view {
						flex: 1;
					}
				}
				.answer {
					display: flex;
					align-items: center;
					padding: 40upx 0;
					border-bottom: 1upx solid #EBEBEB;
					text {
						color: #333333;
						font-size: 30upx;
						margin-right: 53upx;
						width: 90upx;
						height: 44upx;
						border: 1upx solid #C5DFDB;
						border-radius: 22upx;
						text-align: center;
					}
					text:last-child{
						margin-right: 0;
					}
					.checked {
						background-color: #05C6AD;
						color: #FFFFFF;
						border: none;
					}
				}
				.option {
					display: flex;			
					flex-wrap: wrap;
					view {
						width: 33.3%;
						display: flex;
						align-items: center;
						margin-top: 20upx;
						image {
							width: 26upx;
							height: 26upx;
							margin-right: 12upx;
						}
					}
				}
			}
			.single {
				border: none;
				margin: 0;
			}
			.single:nth-child(1),
			.question:nth-child(1){
				margin: 0;
			}
			.question:last-child {
				border: none;
			}
			.single:last-child{
				.answer {
					border: none;
					padding-bottom: 10upx;
				}
			}
		}
		.chart {
			width: 702upx;
			border: 1upx solid #CEE1DF;
			background: #FFFFFF;
			border-radius: 14upx;
			tr {
				display: flex;
				border-bottom: 1upx solid #CEE1DF;
				th {
					flex: 1;
					color: #333333;
					font-size: 30upx;
					height: 84upx;
					text-align: center;
					line-height: 84upx;
					border-right: 1upx solid #CEE1DF;
				}
				th:last-child,td:last-child {
					border: none;
				}
				td {
					height: 64upx;
					flex: 1;
					text-align: center;
					line-height: 64upx;
					border-right: 1upx solid #CEE1DF;
					color: #333333;
					font-size: 30upx;
				}
			}
			tr:last-child {
				border: none;
			}
		}
	}
	.constitutionModular:nth-child(1) {
		margin-top: 0;
	}
	.nextPage {
		width: 392upx;
		height: 70upx;
		background: #05C6AD;
		box-shadow: 0 6upx 18upx 0px rgba(0, 226, 197, 0.35);
		border-radius: 35upx;
		color: #FFFFFF;
		font-size: 30upx;
		line-height: 70upx;
		text-align: center;
		display: table;
		margin: 83upx auto 70upx;
	}
</style>
